
//
//  HMEmotionGridView.m
//  黑马微博-wzy
//
//  Created by Mac on 2017/2/13.
//  Copyright © 2017年 Mac. All rights reserved.
//

#import "HMEmotionGridView.h"
#import "HMEmotion.h"
#import "NSString+Emoji.h"


//表情的最大行数
#define HMEmotionMaxRows 3
//表情的最大列数
#define HMEmotionMaxCols 7
//每页表情的最大数量:最大行数*最大列数-1(因为每页的右下角都是删除按钮)
//[一般为3*7-1=20个]
#define HMEmotionMaxCountPerPage (HMEmotionMaxRows * HMEmotionMaxCols - 1)


@interface HMEmotionGridView()

@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation HMEmotionGridView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //添加右下角的删除按钮
        UIButton *deleteButton = [[UIButton alloc] init];
        [deleteButton setImage:[UIImage imageWithName:@"compose_emotion_delete"] forState:UIControlStateNormal];
        [deleteButton setImage:[UIImage imageWithName:@"compose_emotion_delete_highlighted"] forState:UIControlStateHighlighted];
        self.deleteButton = deleteButton;
        
    }
    return self;
}

//根据传进来的数据展示相应的表情
//重写 emotions的setter 方法
- (void)setEmotions:(NSArray *)emotions{
    _emotions = emotions;
    //添加所有的表情
    for (int i = 0; i < emotions.count; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.adjustsImageWhenHighlighted = NO;
//        button.backgroundColor = HMRandomColor;
        HMEmotion *emotion = emotions[i];
        //emoji 是字符,不是图片
        //当 传入 表情 为图片类型时,emotion.code==nil;当传入表情为emoji 时,emotion.code!=nil
        //判断是否是emoji:0x1f603 (16进制) --> \54367...
        if (emotion.code) {
            //emoji 的大小取决于 按钮上字体的大小
            //meoji 默认是居中显示的
            button.titleLabel.font = [UIFont systemFontOfSize:32];
            [button setTitle:emotion.emoji forState:UIControlStateNormal];

        }else{
            //图片表情
            //根据路径获取图片名
            NSString *str = [NSString stringWithFormat:@"%@/%@", emotion.directory, emotion.png];
            //setImage : 按钮说你是个的图片居中显示
            [button setImage:[UIImage imageNamed:str] forState:UIControlStateNormal];
        }
        
        [self addSubview:button];
    }

    //最后添加 删除 按钮
    [self addSubview:self.deleteButton];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat leftMargin = 10;
    CGFloat topMargin = 0;
    CGFloat buttonW = (self.width - 2 * leftMargin) / HMEmotionMaxCols;
    CGFloat buttonH = (self.height - topMargin) / HMEmotionMaxRows;
    
    
//    int count = self.emotions.count;
    int count = (int)self.subviews.count;
    
    for (int i = 0; i < count; i++) {
        UIButton *btn = self.subviews[i];
        btn.x = leftMargin + (i % HMEmotionMaxCols) * buttonW;
        btn.y = topMargin + (i / HMEmotionMaxCols) * buttonH;
        btn.width = buttonW;
        btn.height = buttonH;
    }

}


@end
